package com.free.framework.lib.network;

import com.free.framework.BuildConfig;
import com.free.framework.lib.utils.ContextHolder;
import com.free.framework.lib.utils.DeviceInfo;
import com.free.framework.lib.utils.MD5Util;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

/**
 * @author 李博
 * @date 16/10/27
 * @desc Fengjr第一张证书2016年11月6日过期, 第二张2018年09月24日过期
 */

public class FjrX509TrustManager implements X509TrustManager {

    private static final String SERVER_CER_PUBLIC_KEY_MD5 = "cf312b4477d5ea68953e741b2f806a8c";
    private static final String SERVER_CER_PUBLIC_KEY_MD5_NEW = "e6c70a2362e08b639371fd680b2b88e5";
    private static final String SERVER_CER_SUBJECT_NAME = "CN=*.fengjr.com,OU=IT,O=北京凤凰理理它信息技术有限公司,L=beijing,ST=beijing,C=CN";

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        if (BuildConfig.DEBUG || DeviceInfo.isNetworkTypeWifi(ContextHolder.getContext())){
            return;
        }

        boolean hasCer = false;
        for (X509Certificate cer : chain) {
            if (cer.getSubjectX500Principal().getName().equals(SERVER_CER_SUBJECT_NAME)) {
                String publicKeyMD5 = MD5Util.toMD5(cer.getPublicKey().toString());
                if (publicKeyMD5.equals(SERVER_CER_PUBLIC_KEY_MD5) || publicKeyMD5.equals(SERVER_CER_PUBLIC_KEY_MD5_NEW)) {
                    hasCer = true;
                    break;
                }
            }
        }

        if (!hasCer) {
            throw new CertificateException("certificate not match");
        }

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[]{};
    }
}
